package org.smart4j.chapter2.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据类型转换工具类
 */
public class CastUtil {

    private static  final Logger logger = LoggerFactory.getLogger(CastUtil.class);

    public static String  castString(Object obj){
        return CastUtil.castString(obj,"");
    }

    public static String castString(Object obj, String s) {
        return obj != null ? String.valueOf(obj):s;
    }

    public static double castDouble(Object obj){
        return CastUtil.castDouble(obj,0);
    }

    public static double castDouble(Object obj,double defaultValue){
        double doubleValue = defaultValue;
        if (obj != null) {
            String string = castString(obj);
            if(StringUtil.isNotEmpty(string)){
                try {
                    doubleValue = Double.parseDouble(string);
                }catch (NumberFormatException e){
                    doubleValue = defaultValue;
                }
            }
        }
        return doubleValue;
    }

    public static long castLong(Object obj){
       return castLong(obj,0);
    }

    public static long castLong(Object obj,long defaultValue){
        long longValue = defaultValue;
        if (obj != null){
            String s = castString(obj);
            if (StringUtil.isNotEmpty(s)){
                try {
                    longValue = Long.parseLong(s);
                }catch (NumberFormatException e){
                    longValue = defaultValue;
                }
            }
        }
        return  longValue;
    }

    public static int castInt(Object obj){
        return castInt(obj,0);
    }

    public static int castInt(Object obj,int defaultValue){
        int intValue = defaultValue;
        if (obj != null){
            String s = castString(obj);
            if (StringUtil.isNotEmpty(s)){
                try {
                    intValue = Integer.parseInt(s);
                }catch (NumberFormatException e){
                    intValue = defaultValue;
                }
            }
        }
        return intValue;
    }

    public static boolean castBoolean(Object obj){
        return castBoolean(obj,false);
    }

    public static boolean castBoolean(Object obj, boolean defaultValue) {
        boolean boolValue = defaultValue;
        if (obj != null){
            boolValue = Boolean.parseBoolean(castString(obj));
        }
        return boolValue;
    }


}
